<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
        <meta name="format-detection" content="telephone=no" />
        <title>发布动态</title>
        <link rel="stylesheet" type="text/css" href="../css/aui.css" />
        <link rel="stylesheet" type="text/css" href="../css/aui-flex.css"/>
        <style type="text/css">
        .img-list{
            padding:5px;
        }
        .img-item{
            width:100%;
            height:80px;
            background-size: cover; 
        }
        .aui-flex-item-4{
            padding: 5px;
        }
        .picGroupCell {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
            padding:15px;
            background: #f3f3f3;
        }
        .deletePic:before{
            content:"-";
            color:#fff;
            position: absolute;
            right: -3px;
            top: -5px;
            font-weight: bold;
            height: 18px;
            width: 18px;
            border-radius: 50%;
            background: #327afa;
            font-size: 18px;
            line-height: 18px;
            text-align: center;
        }
        #formMask{
            position: absolute;left:0;top:0;
            width: 100%;height:100%;
            z-index: 100;
            display: none;
        }
        </style>
    </head>
    <body>
        <header class="aui-bar aui-bar-nav aui-bar-dark" style="background: #327afa;">
            <a class="aui-pull-left" onClick="closeWin();">取消</a>
            <a class="aui-pull-right" tapmode id="submitForm" style="padding-left: 10px;">发布</a>
        </header>

        <div class="aui-content">
            <form class="aui-form" style="position: relative;">
                <div id="formMask"></div>
                <textarea placeholder="这里输入文字" name="text" style="min-height: 80px;border: none;overflow: auto;"></textarea>

                <div class="aui-content">
                    <div class="aui-flex-col img-list">
<!--                         <div class="aui-flex-item-4" style="position: relative;">
                            <div class="img-item" style="background-image: url(http://docs.apicloud.com/img/docImage/junior-develop-guide/jdg_10.png);"></div>
                             <i class="deletePic aui-iconfont aui-icon-close"></i>
                        </div> -->
                        <div class="aui-flex-item-4 picSelect-wrap">
                            <div class="picSelect" tapmode onclick="selectPic(this);">
                                <div class="picGroupCell">
                                    <p><img src="../image/addPic.png"></p>
                                    <p>添加图片</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

    </body>
    <script id="img-template" type="text/x-dot-template">
     <div class="aui-flex-item-4 itemRow" style="position: relative;">
         <div class="img-item" style="background-image: url({{=it}});" data-src="{{=it}}"></div>
         <span class="deletePic" tapmode></span>
     </div>
    </script>
    <script type="text/javascript" src="../script/api.js" ></script>
    <script type="text/javascript" src="../script/common.js" ></script>
    <script type="text/javascript" src="../script/doT.min.js"></script>
    <script type="text/javascript" src="../script/jquery-1.11.3.js"></script>
    <script type="text/javascript">
        function closeWin(){
            api.closeWin({
                animation:{
                    type:"reveal",
                    subType:"from_top", 
                    duration:250,
                    curve:'ease_in_out'
                }
            });
        }

        apiready = function() {
            api.parseTapmode();

            // api.setStatusBarStyle({
            //     style : 'dark'
            // });
            
            var header = $api.dom('header');
            $api.fixIos7Bar(header);

            var preloadImgs=api.pageParam.imageUrls;
            if(preloadImgs&&preloadImgs.length){
                addImageToItem(preloadImgs);
            }
        }

        $(document).ready(function(){
            $('.img-list').delegate('.deletePic','click',function(){
                $(this).closest('.aui-flex-item-4').remove();
            });

            $('#submitForm').click(function(){
                var $form=$('.aui-form');

                showLoading();
                $('#formMask').show();

                var images=[];
                $('.img-item').each(function(){
                    images.push($(this).find('input').val());
                });
                getStorageAll();
                ajaxRequest('Post/add?username='+user_name, 'post', {text:$form.find('[name="text"]').val(),images:images}, function (ret, err) {
                    if(ret.status==1){
                        hideLoading();

                        closeWin();

                        api.sendEvent({
                            name: 'publishPostDone'
                        });

                    }else{
                        api.toast({
                            msg: ret.msg,
                            duration: 2000,
                            location: 'bottom'
                        })
                    }
                    $('#formMask').hide();
                    hideLoading();
                });
            })


            // //单击图片效果
            // $('.img-list').delegate('.img-item','click',function(e){
            //     var imgUrl=$(this).attr('data-src');
            //     var imgList=['fs://'+imgUrl];
            //     api.openWin({
            //         name: 'photobrowser_win',
            //         url: './friend/photobrowser_win.html',
            //         animation:{
            //             type:"fade",               
            //             duration:200
            //         },
            //         pageParam:{
            //             imgList:imgList
            //         }
            //     });
            // });

        });

        function selectPic(obj){
            api.actionSheet({
                title: '请选择图片',
                cancelTitle: '取消',
                buttons: ['相册选取', '魅力自拍']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {

                var UIMediaScanner = api.require('UIMediaScanner');
                UIMediaScanner.open({
                    type: 'picture',
                    column: 4,
                    classify: true,
                    max: 9,
                    sort: {
                        key: 'time',
                        order: 'desc'
                    },
                    texts: {
                        stateText: '已选择*项',
                        cancelText: '取消',
                        finishText: '完成'
                    },
                    styles: {
                        bg: '#fff',
                        mark: {
                            icon: '',
                            position: 'bottom_right',
                            size: 25
                        },
                        nav: {
                            bg: '#eee',
                            stateColor: '#000',
                            stateSize: 17,
                            cancelBg: 'rgba(0,0,0,0)',
                            cancelColor: '#327afa',
                            cancelSize: 17,
                            finishBg: 'rgba(0,0,0,0)',
                            finishColor: '#327afa',
                            finishSize: 17
                        }
                    },
                    scrollToBottom: {
                        intervalTime: -1,
                        anim: false
                    },
                    exchange: true,
                    rotation: true
                }, function(ret) {
                    if (ret) {
                        var listData=ret.list;
                        var thumbPaths=[];
                        if(listData.length){
                            showLoading();
                            for(i in listData){
                                UIMediaScanner.transPath({
                                    path: ret.list[i].path
                                }, function(ret, err) {
                                    if (ret) {
                                        thumbPaths.push(ret.path);
                                    }
                                    if(thumbPaths.length==listData.length){
                                        addImageToItem(thumbPaths);
                                    }
                                });
                            }
                        }
                    }
                });

                //     api.getPicture({
                //         sourceType: 'library',
                //         encodingType: 'jpg',
                //         mediaValue: 'pic',
                //         destinationType: 'base64',
                //         // allowEdit: true,
                //         targetWidth:500,
                //         quality: 60,
                //         saveToPhotoAlbum: false
                //     }, function (ret, err) {
                //         if (ret) {
                //             if (!ret.base64Data) {
                //                 imgBase64 = '';
                //             } else {
                //                 imgBase64 = ret.base64Data;

                //                 alert(JSON.stringify(ret.base64Data));
                //                 // addImageToItem(imgBase64);
                //         }
                //     } else {
                //         api.toast({
                //             msg: err.msg,
                //             duration: 2000,
                //             location: 'bottom'
                //         })
                //     }
                // })
                } else if (ret.buttonIndex == 2) {
                    api.getPicture({
                        sourceType: 'camera',
                        encodingType: 'jpg',
                        mediaValue: 'pic',
                        destinationType: 'base64',
                        // allowEdit: true,
                        targetWidth:500,
                        quality: 60,
                        saveToPhotoAlbum: true
                    }, function (ret, err) {
                        if (ret) {
                            if (!ret.base64Data) {
                                imgBase64 = '';
                            } else {
                                imgBase64 = ret.base64Data;
                                addImageToItem(imgBase64);
                            }
                        } else {
                            api.toast({
                                msg: err.msg,
                                duration: 2000,
                                location: 'bottom'
                            })
                        }
                    })
                }
            });
        }

        function addImageToItem(imageUrls){
            itemCount=$('.img-item').length;
            if(itemCount+imageUrls.length>9){
                api.toast({
                    msg: '上传图片达到上限',
                    duration: 2000,
                    location: 'bottom'
                })
            }else{
                var tpl = $api.byId('img-template').text;
                var tempFn = doT.template(tpl);

                for(var i=0;i<imageUrls.length;i++){
                    if(!$('.itemRow').length){
                        $('.img-list').prepend(tempFn(imageUrls[i]));
                    }else{
                        $('.itemRow:last').after(tempFn(imageUrls[i]));
                    }
                    checkPicSelect();
                }

                //upload
                var uploadFiles=[];
                for(var i=0;i<imageUrls.length;i++){
                    var img = new Image();
                    img.src = imageUrls[i];
                    img.onload = function () {
                        //生成比例
                        var w = this.width, h = this.height, scale = w / h;
                        w = 640 || w;
                        h = w / scale;
                        //生成canvas
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        $api.attr(canvas, 'width', '' + w + '');
                        $api.attr(canvas, 'height', '' + h + '');
                        ctx.drawImage(this, 0, 0, w , h);
                        var base64 = canvas.toDataURL('image/jpeg');

                        uploadFiles.push(base64);
                        if(uploadFiles.length==imageUrls.length){
                            $('#formMask').show();
                            showLoading();

                            var upData = {
                                files: uploadFiles,
                            }
                            getStorageAll();
                            var url = 'Post/imagesUpload?username='+user_name;

                            ajaxRequest(url, 'post', upData, function (ret, err) {
                                if(ret.status==1){
                                    for(var j=0;j<ret.msg.length;j++){
                                        var uploadUrl=ret.msg[j];
                                        $('<input type="hidden" name="images[]" value="'+uploadUrl+'" />').appendTo($('.img-list .img-item').eq($('.img-list .img-item').length-(ret.msg.length-j)));
                                    }
                                }else{
                                    api.toast({
                                        msg: ret.msg,
                                        duration: 2000,
                                        location: 'bottom'
                                    })
                                }
                                $('#formMask').hide();
                                hideLoading();
                            })
                        }
                    }
                }

                // var img = new Image();
                // img.src = imageUrl;
                // img.onload = function () {
                //     //生成canvas
                //     var canvas = document.createElement('canvas');
                //     var ctx = canvas.getContext('2d');
                //     $api.attr(canvas, 'width', '' + this.width + '');
                //     $api.attr(canvas, 'height', '' + this.height + '');
                //     ctx.drawImage(this, 0, 0, this.width , this.height);
                //     var base64 = canvas.toDataURL('image/jpeg');

                //     $('#formMask').show();
                //     showLoading();

                //     var upData = {
                //         file: base64,
                //     }
                //     getStorageAll();
                //     var url = 'Post/imageUpload?username='+user_name;
                //     ajaxRequest(url, 'post', upData, function (ret, err) {
                //         if(ret.status==1){
                //             var uploadUrl=ret.msg;
                //             $('<input type="hidden" name="images[]" value="'+uploadUrl+'" />').appendTo($('.img-list .img-item:last'));
                //         }else{
                //             api.toast({
                //                 msg: ret.msg,
                //                 duration: 2000,
                //                 location: 'bottom'
                //             })
                //         }
                //         $('#formMask').hide();
                //         hideLoading();
                //     })
                // }

                
            }
        }

        function checkPicSelect(){
            itemCount=$('.img-item').length;
              if(itemCount>=9){
                $('.picSelect-wrap').hide();
            }else{
                $('.picSelect-wrap').show();
            }
        } 
    </script>
</html>